
var apiHost = wx.getStorageSync('apiHost');
var yunId = wx.getStorageSync('yunId');
var userInfo = wx.getStorageSync('userInfo');

var Appid = wx.getStorageSync('Appid');
var Secret = wx.getStorageSync('Secret');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: false,   //是否显示面板指示点（轮播图）
    autoplay: true,        //是否自动切换（轮播图）
    interval: 2500,         //自动切换时间间隔（轮播图）
    duration: 1000,         //滑动动画时长（轮播图）
    goodsDetails : '',
    qrcode : 'https://uhuijia-1254600872.cos.ap-beijing.myqcloud.com/8ac7b1ef-296f-4cd8-889f-005d29de156d.jpg',
    showCancelArea: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.countSpecliHeight();   //计算当前页面显示的高度
    var spuId = options.spuId;  //获取京东商品详情中传输过来的spuID
    that.goodsDetails(spuId);   //根据spuid查询商品详情

    var openId = wx.getStorageSync('openId');     //用户openId获取

    if (openId != '') {
      that.setData({
        openId: openId,
        showCancelArea: false
      });
    } else {
      that.setData({
        showCancelArea: true
      });
    }

    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
        });
      }
    })

  },

  //获取商品详情
  goodsDetails: function (spuId){
    var that = this;

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/jd/detail",
      data: {
        id: spuId,
        yunId: yunId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        console.log(res)
        var code = res.data.code

        //判断是否请求成功，不成功的话，返回上一级
        if (code == "10000"){
          var goodsDetailsCon = res.data.data
          that.setData({
            goodsDetails: goodsDetailsCon,
            spuId: spuId,
            rolePicture: goodsDetailsCon.rolePicture
          });
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
          wx.navigateBack({ changed: true });//返回上一页  
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })

  },

  //计算首页特卖商品 高度
  countSpecliHeight: function () {
    var that = this;
    /*获取指定元素高度*/
    var query2 = wx.createSelectorQuery();
    var goodsDetailsHeight = "";

    query2.select('#jdGoodsDetailsBottom').boundingClientRect()
    query2.exec(function (res) {
      goodsDetailsHeight = res[0].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            goodsDetailsHeight: res.windowHeight - goodsDetailsHeight,
          });
        }
      });
    });
  },
  /**
   * 小程序向用户发送消息
   */
  sendMsg: function (e) {
    var that = this;


    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    var nameConImg = e.target.dataset.toggle;

    var goodsDetailsSend = nameConImg.split(",");//以逗号截取
    var goodsName = goodsDetailsSend[0];
    var conPrice = goodsDetailsSend[1];
    var mainImageUrl = goodsDetailsSend[2];
    var conUrl = goodsDetailsSend[3];

    wx.request({
      url: apiHost + "/xcx/message/sendNfTz",
      data: {
        openId: that.data.openId,
        // SessionFrom: conPrice+"优惠券",
        // SessionFrom: "【京东】" + conPrice+"元优惠券",
        SessionFrom: "【京东领券更便宜】立领" + conPrice + "元优惠劵",
        describe: goodsName,
        conUrl: conUrl,
        goodsImg: mainImageUrl
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  //跳转商品详情
  goJdDetail: function (e) {
    var that = this;
    var spuId = e.currentTarget.dataset.toggle;

    // 加载中
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.navigateTo({
      url: '../jdDetails/jdDetails?spuId=' + spuId,
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },
  goIndex : function(){
    // 加载中
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.switchTab({
      url: '../Zindex/Zindex',
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },

  //按钮获取用户信息
  getUserInfo: function (res) {
    var that = this;

    var errMsgFlg = res.detail.errMsg

    if ("getUserInfo:ok" == errMsgFlg) {
      var userCon = res.detail
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurl(userCon, code)
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    }
  },

  /**
  * 解密用户登录完成后的url
  */
  VERBurl: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'xcx/UserInfo/decodeUserInfo',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: Appid,
        Secret: Secret
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果
        if (data.data.status == 1) {
          var userInfo_ = data.data.userInfo;

          var openIdFl = userInfo_.openId;
          var phone = userInfo_.phone;

          wx.setStorageSync('userId', userInfo_.unionId);
          wx.setStorageSync('openId', openIdFl);
          wx.setStorageSync('phone', phone);
          wx.setStorageSync('session_token', userInfo_.session_key);
          wx.setStorageSync('userInfo', userInfo_);

          that.setData({
            showCancelArea: false
          });
        } else {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '网络异常',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }

        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

    /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    var that = this;

    var nameImg = options.target.dataset.toggle;

    var nameImgList = nameImg.split(",");//以逗号截取
    var goodsName = nameImgList[0];
    var mainImageUrl = nameImgList[1];
    var conUrl = nameImgList[2];
    var spuId = nameImgList[3];

    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: "【京东领劵更便宜】"+goodsName,        // 默认是小程序的名称(可以写slogan等)
      path: 'pages/jdDetails/jdDetails',        // 默认是当前页面，必须是以‘/’开头的完整路径
      imgUrl: mainImageUrl,     //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log("转发成功之后的回调")
        }
      },
      fail: function (res) {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          console.log("用户取消转发")
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          console.log("转发失败")
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
    }
    // 来自页面内的按钮的转发
　　if (options.from == 'button') {
  　　　　// 此处可以修改 shareObj 中的内容
      shareObj.path = 'pages/jdDetails/jdDetails?spuId=' + spuId;
　　}
　　// 返回shareObj
　　return shareObj;
},


//测试绘图
textCanvas:function(){
  var that = this;

  wx.downloadFile({
    url: userInfo.avatarUrl,
    success: function (res1) {
      console.log(res1)
      //缓存头像图片
      that.setData({
        portrait_temp: res1.tempFilePath
      })
      //缓存canvas绘制小程序二维码
      wx.downloadFile({
        url: that.data.qrcode,
        success: function (res2) {
          console.log('二维码：' + res2.tempFilePath)
          //缓存二维码
          that.setData({
            qrcode_temp: res2.tempFilePath
          })
          console.log('开始绘制图片')
          that.drawImage();
          wx.hideLoading();
          setTimeout(function () {
            that.canvasToImage()
          }, 200)
        }
      })
    }
  })
},

//绘制canvas图片
drawImage() {
  //绘制canvas图片
  var that = this
  const ctx = wx.createCanvasContext('myCanvas')

  var bgPath = that.data.goodsDetails.banners[0]
  var portraitPath = that.data.portrait_temp
  var hostNickname = userInfo.nickName

  var qrPath = that.data.qrcode_temp
  var windowWidth = that.data.windowWidth
  that.setData({
    scale: 1.6
  })
  //绘制背景图片
  // ctx.drawImage(bgPath, 0, 40, windowWidth, windowWidth/2)

  //绘制头像
  ctx.save()
  ctx.beginPath()
  ctx.arc(windowWidth / 2, 0.32 * windowWidth, 0.15 * windowWidth, 0, 2 * Math.PI)
  ctx.clip()
  ctx.drawImage(portraitPath, 0.7 * windowWidth / 2, 80, 0.3 * windowWidth, 0.3 * windowWidth)
  ctx.restore()
  //绘制第一段文本
  ctx.setFillStyle('#ffffff')
  ctx.setFontSize(0.037 * windowWidth)
  ctx.setTextAlign('center')
  ctx.fillText(hostNickname + ' 正在参加疯狂红包活动', windowWidth / 2, windowWidth / 2)
  //绘制第二段文本
  ctx.setFillStyle('#ffffff')
  ctx.setFontSize(0.037 * windowWidth)
  ctx.setTextAlign('center')
  ctx.fillText('邀请你一起来领券抢红包啦~', windowWidth / 2, 0.57 * windowWidth)
  //绘制二维码
  ctx.drawImage(qrPath, 0.64 * windowWidth / 2, 0.75 * windowWidth, 0.36 * windowWidth, 0.36 * windowWidth)
  //绘制第三段文本
  ctx.setFillStyle('#ffffff')
  ctx.setFontSize(0.037 * windowWidth)
  ctx.setTextAlign('center')
  ctx.fillText('长按二维码领红包', windowWidth / 2, 1.36 * windowWidth)
  ctx.draw();
},

canvasToImage() {
  var that = this
  wx.canvasToTempFilePath({
    x: 0,
    y: 0,
    width: that.data.windowWidth,
    height: that.data.windowWidth * that.data.scale,
    destWidth: that.data.windowWidth * 4,
    destHeight: that.data.windowWidth * 4 * that.data.scale,
    canvasId: 'myCanvas',
    success: function (res) {
      console.log(res.tempFilePath)
      console.log('朋友圈分享图生成成功:' + res.tempFilePath)
      wx.previewImage({
        current: res.tempFilePath, // 当前显示图片的http链接
        urls: [res.tempFilePath] // 需要预览的图片http链接列表
      })
    },
    fail: function (err) {
      console.log('失败')
      console.log(err)
    }
  })
},
  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var openIdFlag = wx.getStorageSync('openId');     //用户openId获取
    //判断openId是否存在
    if (openIdFlag != '') {
      that.setData({
        openId: openIdFlag,
        showCancelArea: false
      });
      that.onLoad();
    } else {
      that.setData({
        showCancelArea: true
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

})